package com.yqg.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yqg.manage.controller.dto.*;
import com.yqg.manage.entity.Archive;
import com.yqg.manage.entity.Case;
import com.yqg.manage.entity.CaseArchiveStage;
import com.yqg.manage.entity.Params;
import com.yqg.manage.mapper.CaseMapper;
import com.yqg.manage.service.IArchiveService;
import com.yqg.manage.service.ICaseArchiveStageService;
import com.yqg.manage.service.ICaseService;
import com.yqg.manage.service.IParamsService;
import com.yqg.manage.utils.TimeUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * CaseServiceImpl 服务实现类
 *
 * @author suzhuang
 * @since 2023-07-05
 */
@Service
public class CaseServiceImpl extends MPJBaseServiceImpl<CaseMapper, Case> implements ICaseService {
    private static final Object lock = new Object(); // 创建一个锁对象
    private static long lastCalledTime = 0; // 记录上一次调用的时间戳
    private static String num;
    @Resource
    private CaseMapper caseMapper;

    @Resource
    private IArchiveService archiveService;

    @Resource
    private ICaseArchiveStageService caseArchiveStageService;

    @Resource
    private IParamsService paramsService;

    @Override
    public HandingDTO[] handing(Long unitId, Long userId) {
        return caseMapper.handing(unitId,userId);
    }

    @Override
    public InformDTO[] inform(Long unitId, Long userId) {
        return caseMapper.inform(unitId,userId);
    }

    @Override
    public CaseCategoryRankingDTO[] caseTypeRanking(Long unitId, Long userId) {
        return caseMapper.caseTypeRanking(unitId,userId);
    }

    @Override
    public CaseResultDTO[] countResult(Long unitId, Long userId) {
        return caseMapper.countResult(unitId,userId);
    }

    @Override
    public List<MontCountDTO> monthCount(Long month,Long unitId,Long userId) {
        // 获取当前时间前mont个月的第一天作为起始日期
        LocalDate startDate = LocalDate.now().minusMonths(month).withDayOfMonth(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

        // 初始化一个空的MontCountDTO列表，用于存放每个月份及对应的初始计数值（0）
        List<MontCountDTO> emptyMontCountList = new ArrayList<>();
        // 遍历从起始日期到当前时间范围内的所有月份
        for (int i = 0; i < month; i++) {
            // 计算当前遍历到的月份
            LocalDate currentMonth = startDate.plusMonths(i);
            // 将当前月份格式化为字符串形式（yyyy-MM）
            String monthStr = currentMonth.format(formatter);
            // 创建一个新的MontCountDTO实例，初始化月份和计数值（0）
            MontCountDTO emptyMontCount = new MontCountDTO(monthStr, 0);
            // 将新的实例添加到emptyMontCountList中
            emptyMontCountList.add(emptyMontCount);
        }

        List<MontCountDTO> allMontCountList = caseMapper.allMontCount(unitId,userId);

        // 使用HashMap存储allMontCountList中的月份与对应计数值，优化查找性能
        Map<String, Integer> countByMonth = new HashMap<>();
        for (MontCountDTO filled : allMontCountList) {
            // 将月份及其对应的计数值存入HashMap
            countByMonth.put(filled.getMont(), filled.getCount());
        }

        // 遍历emptyMontCountList，根据月份从countByMonth中获取实际计数值，并填充到对应的MontCountDTO实例中
        for (MontCountDTO empty : emptyMontCountList) {
            // 获取该月份在数据库中的统计计数值
            Integer count = countByMonth.get(empty.getMont());
            // 如果存在该月份的统计计数值，则将其设置到empty实例中
            if (count != null) {
                empty.setCount(count);
            }
        }

        return emptyMontCountList;
    }

    @Override
    public int ifExist(String caseNum) {
        return caseMapper.ifExist(caseNum);
    }

    @Override
    public synchronized String num() {
        synchronized (lock) { // 获取锁
            long currentTime = System.currentTimeMillis(); // 获取当前时间戳
            long elapsedTime = currentTime - lastCalledTime; // 计算与上一次调用的时间间隔
            if (elapsedTime < 1000) { // 如果时间间隔小于1秒，就睡眠相应时间
                try {
                    Thread.sleep(1000 - elapsedTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            lastCalledTime = System.currentTimeMillis(); // 更新上一次调用的时间戳

            num = TimeUtils.getFormattedTime2(new Date());
        } // 释放锁
        return num;
    }

    @Override
    public Boolean isCaseClosed(Long id) {
        List<Params> caseClosed = caseMapper.getCaseClosed(id);
        return caseClosed != null && !caseClosed.isEmpty();
    }
}
